package com.zcyr.util;

import com.mzlion.easyokhttp.HttpClient;
import com.mzlion.easyokhttp.exception.HttpClientException;
import com.zcyr.pojo.UserInfo;
import com.zcyr.pojo.GiteeUserToken;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class GiteeTool {

    @Value("${tryme.gitee.redirect_uri:null}")
    private String redirect_uri;

    @Value("${tryme.gitee.gitee_client_id:null}")
    private String gitee_client_id;

    @Value("${tryme.gitee.gitee_client_secret:null}")
    private String gitee_client_secret;

    /**
     * 调用gitee接口: https://gitee.com/oauth/token
     * @param code 接口参数
     * @return UserToken 封装好的接口返回值, 如果调用失败则返回null
     */
    public GiteeUserToken getUserToken(String code){
        GiteeUserToken ret = null;
        try{
            // 调用gitee接口
            ret = HttpClient.post("https://gitee.com/oauth/token")
                    .queryString("grant_type", "authorization_code")
                    .queryString("code", code)
                    .queryString("client_id", gitee_client_id)
                    .queryString("redirect_uri", redirect_uri)
                    .queryString("client_secret", gitee_client_secret)
                    .asBean(GiteeUserToken.class);
        }catch (HttpClientException e){
            System.out.println(e.getMessage());
        }
        return ret;
    }

    /**
     * 调用gitee接口: https://gitee.com/api/v5/user
     * @param giteeUserToken 需要UserToken的access_token
     * @return UserInfo 封装了用户的基本资料, 获取失败返回null
     */
    public UserInfo getUserInfo(GiteeUserToken giteeUserToken){
        String access_token = giteeUserToken.getAccess_token();
        UserInfo userInfo = null;
        try{
            userInfo = HttpClient
                    // 请求方式和请求url
                    .get("https://gitee.com/api/v5/user")
                    //设置请求参数
                    .queryString("access_token",access_token)
                    .asBean(UserInfo.class);
        }catch (HttpClientException e){
            System.out.println(e.getMessage());
        }
        return userInfo;
    }
}
